package simpleservlet;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;

public class NettyResponse {
    private ChannelHandlerContext ctx;
    private HttpRequest request;

    public NettyResponse(ChannelHandlerContext ctx,HttpRequest request) {
        this.ctx = ctx;
        this.request = request;
    }

    public void write(String out) throws Exception {
        try {
            if(out == null || out.length() ==0) {
                return;
            }

            FullHttpResponse response = new DefaultFullHttpResponse(
                    HttpVersion.HTTP_1_1,
                    HttpResponseStatus.OK,
                    //包装数组，非池化ByteBuf,netty中的换冲区可以理解为数组
                    Unpooled.wrappedBuffer(out.getBytes("UTF-8"))
            );

            response.headers().set("Content-Type","text/html");
            ctx.write(response);
        } finally {
            //冲刷
            ctx.flush();
            ctx.close();
        }
    }
}
